//
//  YLCEasyCommunicateViewController.m
//  LinYa
//
//  Created by 初程程 on 2018/1/27.
//  Copyright © 2018年 初程程. All rights reserved.
//

#import "YLCEasyCommunicateListViewController.h"
#import "YLCEasyCommunicateView.h"
#import "YLCTitleAndIconModel.h"
#import "YLCProgramListViewController.h"
#import "YLCPayViewController.h"
#import "YLCEasyBuyHomeModel.h"
#import "YLCSynchronizeViewController.h"
@interface YLCEasyCommunicateListViewController ()
@property (nonatomic ,strong)YLCEasyCommunicateView *topEasyView;
@property (nonatomic ,strong)YLCEasyCommunicateView *bottomEasyView;
@end

@implementation YLCEasyCommunicateListViewController
{
    UIImageView *topView;
    UIImageView *topBackView;
    UILabel *tipView;
    UIImageView *bottomView;
    UIScrollView *baseScrollView;
    NSArray *easyList;
    NSArray *easyDataList;
    NSString *ygt_price;
    NSString *ygt_status;//易沟通账号状态  0:没有 1:有效 2:试用 3:过期
}
- (UIBarButtonItem *)rightBarButtonItem{
    return [YLCFactory createTitleBarButtonItemWithTitle:@"同步" titleColor:RGB(255, 255, 255) selector:@selector(synchronize) target:self];
}
- (YLCEasyCommunicateView *)topEasyView{
    if (!_topEasyView) {
        _topEasyView = [[YLCEasyCommunicateView alloc] initWithFrame:CGRectZero];
        
        _topEasyView.backgroundColor = YLC_COMMON_BACKCOLOR;
        
        if (isPad){
            _topEasyView.imageSize = CGSizeMake(75, 75);
        }else{
            _topEasyView.imageSize = CGSizeMake(45, 45);
        }
//
//        _topEasyView.cellSize = CGSizeMake((self.view.frameWidth-1)/3, (self.view.frameWidth-1)/3);
    }
    return _topEasyView;
}
- (YLCEasyCommunicateView *)bottomEasyView{
    if (!_bottomEasyView) {
        _bottomEasyView = [[YLCEasyCommunicateView alloc] initWithFrame:CGRectZero];
        
        _bottomEasyView.backgroundColor = YLC_COMMON_BACKCOLOR;
        
        if (isPad){
            _bottomEasyView.imageSize = CGSizeMake(75, 75);
        }else{
            _bottomEasyView.imageSize = CGSizeMake(45, 45);
        }
        //
        //        _topEasyView.cellSize = CGSizeMake((self.view.frameWidth-1)/3, (self.view.frameWidth-1)/3);
    }
    return _bottomEasyView;
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
//    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
//    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:16], NSFontAttributeName, RGB(67, 67, 67), NSForegroundColorAttributeName, nil];
//
//    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
//
//    [self.navigationController.navigationBar setTintColor:RGB(67, 67, 67)];

    [self initDataSource];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.navigationController.navigationBar setBarTintColor:YLC_THEME_COLOR];
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:16], NSFontAttributeName, [UIColor whiteColor], NSForegroundColorAttributeName, nil];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];

//    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createCustomView];
    [self bindViewModel];
}
- (void)initDataSource{
    
//    NSMutableArray *easyContainer = [NSMutableArray arrayWithCapacity:0];
//    NSArray *titleList = @[@"舒适洁牙",@"牙周治疗",@"牙齿美白",@"根管治疗",@"树脂补牙",@"瓷嵌体",@"无痛拔牙",@"超薄贴面",@"牙齿矫正",@"美学修复",@"活动义齿",@"种植牙",@"儿童齿科",@"CT影像",@"其他"];
//    for (int i = 0; i<titleList.count; i++) {
//        YLCTitleAndIconModel *model = [[YLCTitleAndIconModel alloc] init];
//
//        model.title = titleList[i];
//
//        model.iconName = [NSString stringWithFormat:@"easy_%d",i+1];
//
//        [easyContainer addObject:model];
//    }
//    easyList = easyContainer.copy;
    
    YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
    
    [YLCNetWorking loadNetServiceWithParam:@{@"userId":userModel.user_id} method:@"POST" urlPath:@"app/sygt/index" delegate:self response:^(id responseObject, NSError *error) {
        if (error) {
            return ;
        }
        NSArray *list = responseObject[@"list"];
        NSMutableArray *dataContainer = [NSMutableArray arrayWithCapacity:0];
        
        NSMutableArray *topShowContainer = [NSMutableArray arrayWithCapacity:0];
        
        NSMutableArray *allShowContainer = [NSMutableArray arrayWithCapacity:0];
        
        NSMutableArray *bottomShowContainer = [NSMutableArray arrayWithCapacity:0];
//        for (NSDictionary *dict in list) {
//                    }
        
        if (list.count>6) {
            for (int i = 0; i<6; i++) {
                NSDictionary *dict = list[i];
                YLCEasyBuyHomeModel *model = [YLCEasyBuyHomeModel modelWithDict:dict];
                
                model.classify_id = dict[@"id"];
                
                [dataContainer addObject:model];
                
                YLCTitleAndIconModel *showModel = [[YLCTitleAndIconModel alloc] init];
                
                showModel.iconPath = model.classify_img;
                
                showModel.title = model.classify_name;
                
                [topShowContainer addObject:showModel];
                
                [allShowContainer addObject:showModel];
            }
            for (int i =6; i<list.count; i++) {
                NSDictionary *dict = list[i];
                YLCEasyBuyHomeModel *model = [YLCEasyBuyHomeModel modelWithDict:dict];
                
                model.classify_id = dict[@"id"];
                
                [dataContainer addObject:model];
                
                YLCTitleAndIconModel *showModel = [[YLCTitleAndIconModel alloc] init];
                
                showModel.iconPath = model.classify_img;
                
                showModel.title = model.classify_name;
                
                [bottomShowContainer addObject:showModel];
                
                [allShowContainer addObject:showModel];
            }
        }
        
        easyList = allShowContainer.copy;
        
        easyDataList = dataContainer.copy;
        
        ygt_status = [NSString stringWithFormat:@"%@",responseObject[@"ygt_status"]];
        
        ygt_price = [NSString stringWithFormat:@"%@",responseObject[@"ygt_price"]];
        
        self.topEasyView.listArr = topShowContainer;
        
        self.bottomEasyView.listArr = bottomShowContainer;
    }];
}
- (void)createCustomView{
    baseScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    
    [self.view addSubview:baseScrollView];
    
    topView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"easy_buy_top"]];
    
    topView.frame = CGRectMake(0, 0, self.view.frameWidth, 150);
    
    topBackView.userInteractionEnabled = YES;
    
    [baseScrollView addSubview:topView];
    
    topBackView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"easy_buy_topBack"]];
    
    CGFloat cellWidth = (self.view.frameWidth-20)/3;
    
    CGFloat viewHeight = isPad?150:(topBackView.frameWidth-20)/3-10;
    
//    (topBackView.frameWidth-20)/3-10
    
    topBackView.frame = CGRectMake(10, 30, self.view.frameWidth-20, isPad?320:cellWidth*2);
    
    topBackView.userInteractionEnabled = YES;
    
    [baseScrollView addSubview:topBackView];
    
    tipView = [YLCFactory createLabelWithFont:18 color:[UIColor whiteColor]];
    
    tipView.textAlignment = NSTextAlignmentCenter;
    
    tipView.text = @"[ 透明价格 轻松优选 ]";
    
    [topView addSubview:tipView];
    
    [tipView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(topView.mas_centerX);
        make.top.equalTo(topView.mas_top);
        make.width.equalTo(topView.frameWidth);
        make.height.equalTo(30);
    }];
    
    bottomView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"easy_buy_bottomBack"]];
    
    bottomView.userInteractionEnabled = YES;
    
    [baseScrollView addSubview:bottomView];
    
    bottomView.frame = CGRectMake(10, topBackView.frameMaxY+10, self.view.frameWidth-20, isPad?480:cellWidth*3);
    
    baseScrollView.contentSize = CGSizeMake(self.view.frameWidth, bottomView.frameMaxY);
    
    self.topEasyView.cellSize = CGSizeMake((topBackView.frameWidth-20)/3-10, viewHeight);
    
    self.topEasyView.backgroundColor = [UIColor whiteColor];
    
    [topBackView addSubview:self.topEasyView];
    
    [self.topEasyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsMake(10, 10, 10, 10));
    }];
    
    self.bottomEasyView.cellSize = CGSizeMake((topBackView.frameWidth-20)/3-10, viewHeight);
    
    self.bottomEasyView.backgroundColor = [UIColor whiteColor];
    
    [bottomView addSubview:self.bottomEasyView];
    
    [self.bottomEasyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsMake(10, 10, 10, 10));
    }];
//    [self.view addSubview:self.easyView];
//
//    [self.easyView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(UIEdgeInsetsZero);
//    }];
}
- (void)layoutButtomView{
    
}
- (void)bindViewModel{
    @weakify(self);
    [self.topEasyView.touchSignal subscribeNext:^(id x) {
        @strongify(self);

        NSIndexPath *indexPath = x;
        YLCEasyBuyHomeModel *model = easyDataList[indexPath.row];
        if ([ygt_status isEqualToString:@"1"]) {
            [self goWithIndex:indexPath.row];
        }else{
            if ([ygt_status isEqualToString:@"2"]&&[model.classify_name isEqualToString:@"根管治疗"]) {
                [self goWithIndex:indexPath.row];
            }else{
                [self gotoInfoWithIndex:indexPath.row];
            }

        }
    }];
    
    [self.bottomEasyView.touchSignal subscribeNext:^(id x) {
        @strongify(self);
        
        NSIndexPath *indexPath = x;
        YLCEasyBuyHomeModel *model = easyDataList[indexPath.row+6];
        if ([ygt_status isEqualToString:@"1"]) {
            [self goWithIndex:indexPath.row+6];
        }else{
            if ([ygt_status isEqualToString:@"2"]&&[model.classify_name isEqualToString:@"根管治疗"]) {
                [self goWithIndex:indexPath.row+6];
            }else{
                [self gotoInfoWithIndex:indexPath.row+6];
            }
            
        }
    }];
}

- (void)gotoInfoWithIndex:(NSInteger)index{
    RACSubject *buttonSignal = [RACSubject subject];
    [YLCHUDShow showBuyHUD:buttonSignal];
    [buttonSignal subscribeNext:^(id x) {
        if ([x integerValue]==1) {
            [self gotoTest];
        }else{
            [self gotoPayVc];
        }  
    }];

}
- (void)gotoTest{
    YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
    
    [YLCNetWorking loadNetServiceWithParam:@{@"token":userModel.token,@"userId":userModel.user_id} method:@"POST" urlPath:@"app/sygt/tryUse" delegate:self response:^(id responseObject, NSError *error) {
        if (error) {
            return ;
        }
        [self initDataSource];
        [SVProgressHUD showSuccessWithStatus:@"试用成功"];
    }];
}
- (void)gotoPayVc{
    YLCPayViewController *con = [[YLCPayViewController alloc] init];
    
    [self.navigationController pushViewController:con animated:YES];
}
- (void)goWithIndex:(NSInteger)index{
    YLCEasyBuyHomeModel *model = easyDataList[index];
    
    YLCProgramListViewController *con = [[YLCProgramListViewController alloc] init];
    
    con.classify_id = model.classify_id;

    [self.navigationController pushViewController:con animated:YES];
}
- (void)synchronize{
    if ([ygt_status isEqualToString:@"1"] || [ygt_status isEqualToString:@"2"]) {//已购买
        RACSubject *buttonSignal = [RACSubject subject];
        [YLCHUDShow showSynchronizeHUD:buttonSignal];
        [buttonSignal subscribeNext:^(id x) {
            if ([x integerValue] == 0) {//同步他人模板
                [self synchronizeTemplate:[x integerValue]];
            }else if([x integerValue] == 1){//恢复系统模板
                [self recoveryTemplate];
            }else{//生成您的模板码
                [self synchronizeTemplate:[x integerValue]];
            }
        }];
    }else{//未购买
        [self gotoInfoWithIndex:0];
    }
}
- (void)recoveryTemplate{
    [YLCHUDShow showSelectAlertWithTarget:self Message:@"恢复模板会覆盖现有模板，是否确认同步?" leftTitle:@"确认" rightTitle:@"取消" selector:^(NSInteger index) {
        if (index==0) {
            
            YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
            NSDictionary *parms = @{@"userId":userModel.user_id,
                                    @"token":userModel.token
                                    };
            [YLCNetWorking loadNetServiceWithParam:parms method:@"POST" urlPath:@"app/sygt/syncsys" delegate:self response:^(id responseObject, NSError *error) {
                if (error) {
                    return ;
                }
                [SVProgressHUD showSuccessWithStatus:@"恢复成功"];
            }];
        }else{
            [self synchronize];
        }
    }];
}
- (void)synchronizeTemplate:(NSInteger)type{
    if (type == 2) {
        YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
        NSDictionary *parms = @{@"userId":userModel.user_id,
                                @"token":userModel.token
                                };
        [YLCNetWorking loadNetServiceWithParam:parms method:@"POST" urlPath:@"app/sygt/createCode" delegate:self response:^(id responseObject, NSError *error) {
            if (error) {
                return ;
            }
            NSString *code = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
            
            YLCSynchronizeViewController *con = [[YLCSynchronizeViewController alloc] init];
            
            con.type = type;
            
            con.code = code;
            
            con.title = @"生成您的模板码";
            
            [self.navigationController pushViewController:con animated:YES];
            
        }];
        return;
    }
    YLCSynchronizeViewController *con = [[YLCSynchronizeViewController alloc] init];
    
    con.type = type;
    
    con.title = @"同步模板";
    
    [self.navigationController pushViewController:con animated:YES];
}
- (NSString *)title{
    return @"易沟通";
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
